﻿using System;
using System.Collections.Generic;

using Xc.DataAccess.Core.Extensions;
namespace Xc.DataAccess.PcpChannels
{
    /// <summary>
    /// 下发数据
    /// </summary>
    public abstract class RequestFrame : Frame, IRequestFullFrame
    {

        /// <summary>
        /// 起始标致
        /// </summary>
        public ushort Start { get;private set; } = Starter;
        /// <summary>
        /// 版本号
        /// </summary>
        internal byte FrameVersion { get; set; } = 1;
        /// <summary>
        /// 消息码
        /// </summary>
        public abstract MessageCode MessageCode { get; }

        /// <summary>
        /// 校验码
        /// </summary>
        public ushort CheckCode
        {
            get
            {
                List<byte> datas = new List<byte>();
                datas.AddRange(Start.FromUInt16BigEndian());
                datas.Add(FrameVersion);
                datas.Add((byte)MessageCode);
                datas.Add(0);
                datas.Add(0);
                datas.AddRange(DataAreaLength.FromUInt16BigEndian());
                if (DataArea != null)
                {
                    datas.AddRange(DataArea);
                }
                return CrcCheck(datas.ToArray());
            }
        }
        /// <summary>
        /// 数据域长度
        /// </summary>
        public ushort DataAreaLength
        {
            get
            {
                if (DataArea == null)
                {
                    return 0;
                }
                return (ushort)DataArea.Length;
            }
        }
        /// <summary>
        /// 数据域
        /// </summary>
        public abstract byte[] DataArea { get; }

        public byte[] FullFrame 
        {
            get
            {
                List<byte> datas = new List<byte>();
                datas.AddRange(Start.FromUInt16BigEndian());
                datas.Add(FrameVersion);
                datas.Add((byte)MessageCode);
                datas.AddRange(CheckCode.FromUInt16BigEndian());
                datas.AddRange(DataAreaLength.FromUInt16BigEndian());
                if (DataArea != null)
                {
                    datas.AddRange(DataArea);
                }
                return datas.ToArray();
            }
        }
    }
}
